package net.bitacademy.java22.service;

//서비스로 돌아가는 임포터.

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;

public class Trigger extends Service{
	public static final Context context = null;
	
	static org.jfedor.nxtremotecontrol.NXT robot;
	static AudioManager mAm;
	static WifiManager wifiManager; 
	static BluetoothAdapter mBluetoothAdapter;
	
	EventImportor importor;
	PascalEngine engine;
	static boolean run;
	
	private static Trigger trigger = null;
	public static Trigger getInstance() {
		if(trigger == null)
			trigger = new Trigger();
		return trigger;
	}
	
	public void onCreate() {
		super.onCreate();
		
		mAm = (AudioManager)getSystemService(AUDIO_SERVICE);
        wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        
        Intent intent = new Intent("org.jfedor.nxtremotecontrol.connect");
        bindService(intent, srvConn, BIND_AUTO_CREATE);
//        
//		ProfileHandler ph = new ProfileHandler(this);
//		ph.rollback();
	}

	
	
	public void onDestroy() {
		super.onDestroy();
		run=false;
//		if(robot!=null){
//			Log.d("원격제어끝", "NOT NULL");
//			unbindService(srvConn);
//		//	robot = null;
//		}else{
//			Log.d("원격제어끝", "null");
//		}
	}

	public int onStartCommand (Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		Log.d("Trigger", "onStartCommand");
		importor = new EventImportor(this);
		engine = new PascalEngine(this);
		run=true;
		importor.start();
		engine.start();
		return START_STICKY;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	ServiceConnection srvConn = new ServiceConnection() {
		public void onServiceConnected(ComponentName classname, IBinder binder) {
			Log.d("원격제어끝", "시작");
			robot = org.jfedor.nxtremotecontrol.NXT.Stub.asInterface(binder);
		}
		public void onServiceDisconnected(ComponentName classname) {
			Log.d("원격제어끝", "끝");
			robot = null;
		}
	};
}

